<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
 * ============================================================================
 * 2015-11-21
 */
namespace Home\Controller;
use Home\Logic\UsersLogic;
use Think\Page;
use Think\Verify;

class UserController extends BaseController {

	public $user_id = 0;
	public $user = array();
	
    public function _initialize() {      
        parent::_initialize();



        if(session('?user'))
        {
        	$user = session('user');
            $user = M('users')->where("user_id = {$user['user_id']}")->find();
            session('user',$user);  //覆盖session 中的 user               
        	$this->user = $user;
        	$this->user_id = $user['user_id'];
        	$this->assign('user',$user); //存储用户信息
        	$this->assign('user_id',$this->user_id);
        }else{
        	$nologin = array(
        			'login','pop_login','do_login','logout','verify','set_pwd','finished',
        			'verifyHandle','reg','send_sms_reg_code','identity','check_validate_code',
        			'forget_pwd','check_captcha','check_username','send_validate_code',
        	);
        	if(!in_array(ACTION_NAME,$nologin)){
        		header("location:".U('Home/User/login'));
        		exit;
        	}
        }
      /*  //用户中心面包屑导航
        $navigate_user = navigate_user();
        $this->assign('navigate_user',$navigate_user);



        dump($navigate_user);*/
        //userleft 父级菜单展开
        $action_name=strtolower(ACTION_NAME);
        $vendor_arr=array('add_seller','seller_list');//我是卖家
        $bayer_arr=array('order_list','goods_collect','order_pay','order_pay1','my_ask_buy_detail');//我是买家
        $pay_arr=array('my_money','money_addjl','money_cash','money_cashjl','money_payments','money_frozen');//我是买家
        $info_arr=array('info','password','mobile_validate','email_validate');//信息管理
        $tousu_arr=array('my_complain','my_complain_detail');//我的投诉

        if(in_array($action_name,$vendor_arr)){
            $this->assign('is_vendor',1);
        }elseif(in_array($action_name,$bayer_arr)){
            $this->assign('is_bayer',1);
        }elseif(in_array($action_name,$pay_arr)){
            $this->assign('is_pay',1);
        }elseif(in_array($action_name,$info_arr)){
            $this->assign('is_info',1);
        }elseif(in_array($action_name,$tousu_arr)){
            $this->assign('is_tousu',1);
//        }elseif($action_name=='binding'){
//            $this->assign('is_binding',1);
        }
    }






    public function jd_test(){


        echo "功能待开发！";exit;

        //K/3 Cloud 业务站点地址
            $cloudUrl = "http://192.168.18.133/k3cloud/";
            //登陆参数
            $data = array(
                '55b828ecd6fc90',//帐套Id
                'demo',//用户名
                '888888',//密码
                2052//语言标识
            );

            //定义记录Cloud服务端返回的Session
            $cookie_jar = tempnam('./tmp','CloudSession');
            $post_content = $this->create_postdata($data);

            $result = $this->invoke_login($cloudUrl,$post_content,$cookie_jar);

            //$array = json_decode($result,true);
            header("Content-type: text/html; charset=gb2312");
            echo '<pre>';print_r('登陆请求数据：');
            echo '<pre>';print_r($post_content);

            echo '<pre>';print_r('登陆返回结果：');
            echo '<pre>';print_r($result);

            $data_model = '{"Creator":"String","NeedUpDateFields":[],"Model":{"FID":0,"FBillTypeID":{"FBillTypeID":"","FNUMBER":"XSCKD01_SYS"},"FSaleOrgId":{"FOrgID":0,"FNUMBER":"103"},"FCustomerID":{"FCUSTID":0,"FNUMBER":"CUST0002"},"FStockOrgId":{"FOrgID":0,"FNUMBER":"101.2"},"FOwnerIdHead":{"FItemID":0,"FNUMBER":"103"},"FNote":"","SAL_OUTSTOCK__FEntity":[{"FMaterialID":{"FNumber":"1.01.001"},"FUnitID":{"FNumber":"Pcs","FName":""},"FStockID":{"FNumber":"CK001"},"FStockStausID":{"FNumber":"KCZT01_SYS"},"FMustQty":1,"FRealQty":1,"FAmount":0,"FPrice":0,"FTaxPrice":0,"FDiscount":0,"FDiscountRate":0,"FIsFree":true,"FLot":{"FNUMBER":"0000"}}],"SAL_OUTSTOCK__SubHeadEntity":{"FSettleCurrID":{"FCURRENCYID":0,"FNumber":"PRE001"},"FLocalCurrID":{"FCURRENCYID":0,"FNumber":"PRE001"},"FSettleOrgID":{"FOrgID":0,"FNumber":"103"},"FExchangeTypeID":{"FRATETYPEID":0,"FNumber":"HLTX01_SYS"},"FExchangeRate":"1","FBillAllAmount":0}}}';
            $data = array(
                'SAL_OUTSTOCK',//业务对象标识FormId
                $data_model//具体Json字串
            );

            $post_content = $this->create_postdata($data);

            $result = $this->invoke_save($cloudUrl,$post_content,$cookie_jar);

            //$array = json_decode($result,true);
            echo '<pre>';print_r('销售出库单请求数据：');
            echo '<pre>';print_r($post_content);

            echo '<pre>';print_r('保存返回结果：');
            echo '<pre>';print_r($result);
    }



    //登陆
    public function invoke_login($cloudUrl,$post_content,$cookie_jar)
    {
        $loginurl = $cloudUrl.'Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc';
        return $this->invoke_post($loginurl,$post_content,$cookie_jar,TRUE);
    }

//保存
    public function invoke_save($cloudUrl,$post_content,$cookie_jar)
    {
        $invokeurl = $cloudUrl.'Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc';
        return $this->invoke_post($invokeurl,$post_content,$cookie_jar,FALSE);
    }

//审核
    public function invoke_audit($cloudUrl,$post_content,$cookie_jar)
    {
        $invokeurl = $cloudUrl.'Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc';
        return $this->invoke_post($invokeurl,$post_content,$cookie_jar,FALSE);
    }

    public function invoke_post($url,$post_content,$cookie_jar,$isLogin)
    {
        $ch = curl_init($url);

        $this_header = array(
            'Content-Type: application/json',
            'Content-Length: '.strlen($post_content)
        );

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_content);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if($isLogin){
            curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
        }
        else{
            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

//构造Web API请求格式
   public  function create_postdata($args) {
        $postdata = array(
            'format'=>1,
            'useragent'=>'ApiClient',
            'rid'=>$this->create_guid(),
            'parameters'=>$args,
            'timestamp'=>date('Y-m-d'),
            'v'=>'1.0'
        );
        return json_encode($postdata);
    }

//生成guid
   public function create_guid() {
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
            .substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12)
            .chr(125);// "}"
        return $uuid;
    }




  public function complain(){
        $data=I();
        if(!$data['content'])
            $this->error('内容不能为空！',U('index'));
        $data['status']=0;
        $data['add_time']=time();
        $data['user_id']=$_SESSION['user']['user_id'];
        $res=M('complain')->add($data);
        if($res){
           $this->success('提交成功，工作人员将会尽快处理你的投诉内容，并反馈与您。',U('index'));
        }else{
           $this->error('提交失败,请重试！',U('index'));
        }
  }



    /*
     * 用户中心首页
     */
    public function index(){

        $logic = new UsersLogic();
        $user = $logic->get_info($this->user_id);
        $user = $user['result'];
        $level = M('user_level')->select();
        $level = convert_arr_key($level,'level_id');


        //买家统计
        $buyer_where['user_id']=$_SESSION['user']['user_id'];
        $buyer_where['is_delete']=0;
//        $buyer_where['order_status']=array('in','0,1,2,5,6');
        $buyer_all_num=M('order1')->where($buyer_where)->count();//总数量

        $buyer_where['pay_status']=0;
        $buyer_nopay_num=M('order1')->where($buyer_where)->count();//待付款数量 ok

        $buyer_where['pay_status']=1;
        $buyer_where['order_status']=1;
        $buyer_guohu_num=M('order1')->where($buyer_where)->count();//过户中数量

        $buyer_where['pay_status']=1;
        $buyer_where['order_status']=2;
        $buyer_tuikuan_num=M('order1')->where($buyer_where)->count();//退款中数量

        $buyer_where['pay_status']=1;
        $buyer_where['order_status']=6;
        $buyer_wancheng_num=M('order1')->where($buyer_where)->count();//已完成数量

        $buy_where['user_id']=$_SESSION['user']['user_id'];
        $buy_where['status']=0;
        $qiugou_num =M('ask_buy')->where($buy_where)->count();//求购待确认数量





         //卖家统计
        $vendor_where['user_id']=$_SESSION['user']['user_id'];
        $vendor_where['is_delete']=0;

        $vendor_all_num=M('goods')->where($vendor_where)->count();//总数量  （没删除，userid=自己）

        $vendor_where['status']=5;
        $vendor_where['pay_cate_status']=0;
        $vendor_where['is_submit']=0;
        $vendor_xiajia_num=M('goods')->where($vendor_where)->count();//已下架（没删除，userid=自己，状态0 提交0 审核0）

        $vendor_where['pay_cate_status']=0;
        $vendor_where['status']=0;
        $vendor_where['is_submit']=1;
        $vendor_daiqueren_num=M('goods')->where($vendor_where)->count();//待审核数量（没删除，userid=自己，状态0 提交1 审核0）

        $vendor_where1['status']=1;
        $vendor_where1['is_delete']=0;
        $vendor_where1['user_id']=$_SESSION['user']['user_id'];
        $vendor_zaishou_num=M('goods')->where($vendor_where1)->count();//在售中数量 （没删除，userid=自己，状态1 ）

        $vendor_where2['is_delete']=0;
        $vendor_where2['user_id']=$_SESSION['user']['user_id'];
        $vendor_where2['status']=3;
        $vendor_guohu_num=M('goods')->where($vendor_where2)->count();//正在交易（没删除，userid=自己，状态3 ）
        $vendor_where2['status']=4;
        $vendor_wancheng_num=M('goods')->where($vendor_where2)->count();//已完成（没删除，userid=自己，状态4 ）

        //查询公告
        $where_a['open']=1;
        $where_a['cat_id']=5;
        $article_list =M('Article')->where($where_a)->order('add_time DESC ,article_id DESC')->limit(4)->select();

        //问答
        $qa_list = M('question_answer')->where("status=1")->limit(3)->select();
        $this->assign('qa_list',$qa_list);
        $this->assign('article_list',$article_list);
        $this->assign('vendor_all_num',$vendor_all_num);
        $this->assign('vendor_zaishou_num',$vendor_zaishou_num);
        $this->assign('vendor_xiajia_num',$vendor_xiajia_num);
        $this->assign('vendor_daiqueren_num',$vendor_daiqueren_num);
        $this->assign('vendor_guohu_num',$vendor_guohu_num);
        $this->assign('vendor_wancheng_num',$vendor_wancheng_num);
        $this->assign('buyer_all_num',$buyer_all_num);
        $this->assign('buyer_nopay_num',$buyer_nopay_num);
        $this->assign('buyer_guohu_num',$buyer_guohu_num);
        $this->assign('buyer_tuikuan_num',$buyer_tuikuan_num);
        $this->assign('buyer_wancheng_num',$buyer_wancheng_num);
        $this->assign('qiugou_num',$qiugou_num);
        $this->assign('level',$level);
        $this->assign('user',$user);

        $this->display();
    }

    /************************************************** 我是卖家 *****************************************************/

    /**
     * 我出售的网店
     */
    public function seller_list(){
        $where['is_delete']=0;
        $where['user_id']=$this->user_id;
//        $where = 'is_delete=0 and user_id='.$this->user_id ;
         if(I('status_id')==1) {//待确认
             $where['status']=0;
             $where['is_submit']=1;
//            $where.=' and status =0 ';
        }elseif(I('status_id')==2){//在售中
             $where['status']=1;
//            $where.=' and status =1 ';
        }elseif(I('status_id')==3){//交易中
             $where['status']=3;
        }elseif(I('status_id')==4){//交易完成
             $where['status']=4;
//             $where.=' and status =4 ';
        }elseif(I('status_id')==5){//主动下架
             $where['status']=5;
//        }elseif(I('status_id')==6){//待上架

        }



        $count = M('goods')->where($where)->count();
        $Page = new Page($count,10);
        $show = $Page->show();
        $order_str = "goods_id DESC";
        $list = M('goods')->order($order_str)->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('page',$show);
        $this->assign('lists',$list);
        $this->display();
    }
    /**
     * 我的店铺
     */
/*    public function my_seller(){
        $where['user_id']=$_SESSION['user']['user_id'];
        $seller_list=M('goods')->where($where)->select();
        $this->assign('lists',$seller_list);
        $this->assign('xuhao',1);
        $this->display();
    }*/


    /**
     * 删除店铺
     */
    public function del_seller(){
        $goods_id =I('goods_id');
        $goods=M('goods')->where("goods_id=$goods_id")->find();
        if($goods['status']==1){
            $this->error('该商品在售中，请下架后再删除',U('seller_list'));
        }else{

//            $res=M('goods')->where("goods_id=$goods_id")->delete();
            $up_data['goods_id']=$goods_id;
            $up_data['is_delete']=1;
            $up_data['is_submit']=0;
            $res=M('goods')->save($up_data);
            if($res){
                $this->success('删除成功',U('seller_list'));
            }else{
                $this->error('删除失败,请重试！',U('seller_list'));
            }
        }

    }


    /**
     * 下架
     */
    public function xiajia(){
        $goods_id =I('goods_id');
        $up_data['goods_id']=$goods_id;
        $up_data['status']=5;
        $up_data['is_submit']=0;
       /* if(I('type_id')==1){
            $up_data['seller_check']=0;
        }else{
            $up_data['seller_check']=2;
        }*/
        $up_data['seller_check']=0;

        $res=M('goods')->save($up_data);
        if($res){
            $this->success('操作成功');
        }else{
            $this->error('操作失败,请重试！');
        }
    }



    /**
     * 我要卖店
     */
    public function add_seller(){
        $user_id=$_SESSION['user']['user_id'];
        $user=M('users')->where(array('user_id'=>$user_id))->find();
        if(!$user['mobile']){
            $this->error('需要绑定手机才可可进行交易，请绑定！',U('Home/User/mobile_validate',array('step'=>1)));
        }

        if(IS_POST){
            $data=I();

            $zj_str='';
            foreach($data['zhengjian'] AS $k=>$v){
                $zj_str?$zj_str.=','.$v:$zj_str.=$v;
            }

            $data['weigui_log']=$data['koufen_1'].'-'.$data['koufen_2'].'-'.$data['koufen_3'];

            $data['papers']=$zj_str;
            $data['user_id']=$_SESSION['user']['user_id'];
            $data['add_time']=time();
            $data['seller_cate_id']=2;//类型 2=用户自行提交商品
            $data['seller_check']=0;
            $data['is_submit']=1;
            $data['status']=0;

            unset($data['seller_type1']);
            unset($data['zhengjian']);
            unset($data['koufen_1']);
            unset($data['koufen_2']);
            unset($data['koufen_3']);
            unset($data['__hash__']);




            if($data['goods_id']>0){
                $res= M('goods')->save($data);
                if($res){

                    $config = tpCache('shop_info');
                    if($config['admin_email']){
                        $to=$config['admin_email'];
                        $title='新卖店通知';
                        $content=get_email_content_g($data['goods_id']);
                        new_send_email($to,$title,$content);

                    }
                    $this->success('修改成功',U('seller_list'));
                }else{
                    $this->error('修改失败，请重试！');
                }
            }else{

                $res= M('goods')->add($data);

                if($res){
                    $config = tpCache('shop_info');
                    if($config['admin_email']){

                        $to=$config['admin_email'];
                        $title='新卖店通知';
                        $content=get_email_content_g($res);
                        new_send_email($to,$title,$content);

                    }
                    $this->success('提交成功',U('seller_list'));exit;
                }else{
                    $this->error('提交失败，请重试！');exit;
                }
            }

        }
		$type_id=I('type_id');
        $goods_id=I('goods_id');
        if($goods_id){
            $goods=M('goods')->where("goods_id=$goods_id")->find();

            $weigui_log_arr=explode('-',$goods['weigui_log']);

            $papers_arr=explode(',',$goods['papers']);

            $this->assign('weigui_log_arr',$weigui_log_arr);
            $this->assign('papers_arr',$papers_arr);
            $this->assign('goods',$goods);
        }
        $city =  M('region')->where(array('parent_id'=>$goods['province'],'level'=>2))->select();
        $this->assign('city',$city);

        $p = M('region')->where(array('parent_id'=>0,'level'=> 1))->select();
        $this->assign('province',$p);


        //店铺类型
        $storeType_tm=C('storeType_tm');//天猫
        $this->assign('storeType_tm', $storeType_tm);

        $storeType_jd=C('storeType_jd');//京东
        $this->assign('storeType_jd', $storeType_jd);




        //商标类型
        $brandType=C('brandType');
        $this->assign('brandType', $brandType);


        //所属行业
        $goodsTrade=C('goodsTrade');
        $this->assign('goodsTrade', $goodsTrade);

        $type_list =M('goods_type')->select();
        $this->assign('type_list',$type_list);

		$this->assign('type_id',$type_id);
        $this->display();

    }






    /************************************************** 我的余额  *****************************************************/


    /**
     * 我的余额
     */
    public function my_money(){
        $user_id=$_SESSION['user']['user_id'];


        if(IS_POST){

            //支付      功能待开发

            dump(I());exit;

        }
        $user_money=M('users')->where("user_id=$user_id")->getField('user_money');
        $this->assign('user_money',$user_money);
        $this->display();
    }


    public function add_order(){
        $user = session('user');
        $data['user_id'] = $user['user_id'];
        $data['nickname'] = $user['nickname'];
        $data['account'] = I('money');
        $data['order_sn'] = 'recharge'.get_rand_str(10,0,1);
        $data['ctime'] = time();

        $order_id = M('recharge')->add($data);

        if($order_id){
//            $url = U('Payment/getPay',array('pay_radio'=>$_REQUEST['pay_radio'],'order_id'=>$order_id));
            $url = U('User/order_pay',array('order_id'=>$order_id,'type'=>'recharge'));
            redirect($url);
        }else{
            $this->error('提交失败,参数有误!');
        }
//        $this->display();
    }



    /**
     * 登出
     */
    public function logout(){
    	setcookie('uname','',time()-3600,'/');
    	setcookie('cn','',time()-3600,'/');
    	setcookie('user_id','',time()-3600,'/');
        session_unset();
        session_destroy();
        //$this->success("退出成功",U('Home/Index/index'));
        header("location:".U('Home/Index/index'));
        exit;
    }

    /*
     * 账户资金
     */
    public function account(){
        $user = session('user');
        //获取账户资金记录
        $logic = new UsersLogic();
        $data = $logic->get_account_log($this->user_id,I('get.type'));
        $account_log = $data['result'];

        $this->assign('user',$user);
        $this->assign('account_log',$account_log);
        $this->assign('page',$data['show']);
        $this->assign('active','account');
        $this->display();
    }
    /*
     * 优惠券列表
     */
    public function coupon(){
        $logic = new UsersLogic();
        $data = $logic->get_coupon($this->user_id,$_REQUEST['type']);
        $coupon_list = $data['result'];
        $this->assign('coupon_list',$coupon_list);
        $this->assign('page',$data['show']);
        $this->assign('active','coupon');
        $this->display();
    }
	
    public function couponlist(){
	
			$cateid = I('get.cateid',0); // 当前分类id
			$logic = new UsersLogic();

			$data = $logic->get_couponlist('5',$cateid,$this->user_id);
			$coupon_list = $data['result'];
			$this->assign('coupon_list',$coupon_list);
			$this->assign('page',$data['show']);
			$this->assign('active','coupon');
			$this->display();
		/*
		$logic = new UsersLogic();
        $data = $logic->get_couponlist('5');
        $coupon_list = $data['result'];
        $this->assign('coupon_list',$coupon_list);
        $this->assign('page',$data['show']);
        $this->assign('active','coupon');
        $this->display();*/
    }
	
	public function save_coupon()
    {
        $id = I('get.id');
        //检查是否有积分，余额支付
        $logic = new UsersLogic();
		$result = $logic->coupon_save($this->user_id,$id);
        exit(json_encode($result));
    }
    /**
     *  登录
     */
    public function login(){
		//echo encrypt("123456");
        if($this->user_id > 0){
        	header("Location: ".U('Home/User/index'));
        }           
        $referurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : U("Home/User/index");
        $this->assign('referurl',$referurl);
        $this->display();
    }
	
    public function ajaxl(){

        if($this->user_id > 0){
        	header("Location: ".U('Home/User/index'));
        }           
        $referurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : U("Home/User/index");
        $this->assign('referurl',$referurl);
        $this->display();
    }

    public function pop_login(){
    	if($this->user_id > 0){
    		header("Location: ".U('Home/User/index'));
    	}
        $referurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : U("Home/User/index");
        $this->assign('referurl',$referurl);
    	$this->display();
    }
    
    public function do_login(){
    	$username = I('post.username');
    	$password = I('post.password');
        $username = trim($username);
        $password = trim($password);        
    	$verify_code = I('post.verify_code');
     
         $verify = new Verify();
        if (!$verify->check($verify_code,'user_login'))
        {
             $res = array('status'=>0,'msg'=>'验证码错误');
             exit(json_encode($res));
        }
    	         
    	$logic = new UsersLogic();



    	$res = $logic->login($username,$password);
        
    	if($res['status'] == 1){

    		$res['url'] =  urldecode(I('post.referurl'));
    		session('user',$res['result']);
    		setcookie('user_id',$res['result']['user_id'],null,'/');
    		setcookie('is_distribut',$res['result']['is_distribut'],null,'/');
    		$nickname = empty($res['result']['nickname']) ? $username : $res['result']['nickname'];


            setcookie('uname',$nickname,null,'/');
//            setcookie('uname',urlencode($nickname),null,'/');
            setcookie('cn',0,time()-3600,'/');


            M('users')->where("user_id = {$res['result']['user_id']}")->save(array('last_login'=>time()));

    		$cartLogic = new \Home\Logic\CartLogic();
    		$cartLogic->login_cart_handle($this->session_id,$res['result']['user_id']);  //用户登录后 需要对购物车 一些操作
    	}
    	exit(json_encode($res));
    }
    /**
     *  注册
     */
    public function reg(){
    	if($this->user_id > 0) header("Location: ".U('Home/User/index'));
        if(IS_POST){
            $logic = new UsersLogic();
            //验证码检验
//            $this->verifyHandle('user_reg');
            $nickname = I('post.username','');
            $username = I('post.mobile','');
            $password = I('post.password','');
            $password2 = I('post.password2','');
            $qq = I('post.qqnum','');
            $code = I('post.code','');
            //是否开启注册短信验证码机制

            if(check_mobile($username) && tpCache('sms.regis_sms_enable')){
                if(!$code)
                    $this->error('请输入短信验证码');
                $check_code = $logic->sms_code_verify($username,$code,$this->session_id);
                if($check_code['status'] != 1)
                    $this->error($check_code['msg']);
            }
            //是否开启注册邮箱验证码机制
            if(check_email($username) && tpCache('smtp.regis_smtp_enable')){
                if(!$code)
                    $this->error('请输入邮箱验证码');
                $check_code = $logic->check_validate_code($code, $username);
                if($check_code['status'] != 1)
                    $this->error($check_code['msg']);
            }
            $data = $logic->reg($username,$password,$password2);
            if($data['status'] != 1)
                $this->error($data['msg']);


            $user_id=$data['result']['user_id'];
            $up_data['qq']=$qq;
            $up_data['nickname']=$nickname;
            $res=M('users')->where("user_id=$user_id")->save($up_data);


            session('user',$data['result']);
    		setcookie('user_id',$data['result']['user_id'],null,'/');
    		setcookie('is_distribut',$data['result']['is_distribut'],null,'/');
            $nickname = empty($data['result']['nickname']) ? $username : $data['result']['nickname'];
            setcookie('uname',urlencode($nickname),null,'/');
            $cartLogic = new \Home\Logic\CartLogic();
            $cartLogic->login_cart_handle($this->session_id,$data['result']['user_id']);  //用户登录后 需要对购物车 一些操作
            
            $this->success($data['msg'],U('Home/User/index'));
            exit;
        }
        $validate_code = session('validate_code');
        $send_time=$validate_code['time'];
        $stime=$send_time-time();
        $stime>0?$stime=$stime:$stime=0;
        $this->assign('stime', $stime); //  刷新页面后还有多长时间

      /*  if($stime>0){
        }else{

        }*/
        $this->assign('regis_sms_enable',tpCache('sms.regis_sms_enable')); // 注册启用短信：
        $this->assign('regis_smtp_enable',tpCache('smtp.regis_smtp_enable')); // 注册启用邮箱：
        $sms_time_out = tpCache('sms.sms_time_out')>0 ? tpCache('sms.sms_time_out') : 60;

        $this->assign('sms_time_out', $sms_time_out); // 手机短信超时时间
        $this->display();
    }

    /**
     * 订单支付
     */
    public function order_pay(){

        $order_id=I('order_id');
        $type=I('type');

        if($type=='recharge'){
            $where['order_id']=$order_id;
            $order=M('recharge')->where($where)->find();
        }else{
            $where['order_id']=$order_id;
            $order=M('order1')->where($where)->find();
            if($order['pay_status']==1)
                $this->error('商品完成支付');
            $g_where['goods_id']=$order['goods_id'];
            $goods=M('goods')->where($g_where)->find();

            if($goods['status']!=1){
                /*$up_o_data['order_id']=$order_id;
                $up_o_data['is_delete']=1;
                $res=M('order1')->save($up_o_data);*/
                $this->error('商品已下架',U('order_list'));
            }

        }

        //支付方式


        $paymentList = M('Plugin')->where("`type`='payment' and status = 1 and  scene in(0,2)")->select();
        $paymentList = convert_arr_key($paymentList, 'code');

        foreach($paymentList as $key => $val)
        {

                $val['config_value'] = unserialize($val['config_value']);
                if($val['config_value']['is_bank'] == 2)
                {
                    $bankCodeList[$val['code']] = unserialize($val['bank_code']);
                }


        }
        $bank_img = include 'Application/Home/Conf/bank.php'; // 银行对应图片
        $this->assign('paymentList',$paymentList);
        $this->assign('bank_img',$bank_img);



        $this->assign('type', $type); // 手机短信超时时间
        $this->assign('order', $order); // 手机短信超时时间
        $this->assign('goods_type', $goods['goods_type']); // 手机短信超时时间
        $this->display();
    }





    /**
     * 订单列表
     */
    public function order_list(){

        $where['is_delete']=0;
        $where['user_id']=$this->user_id;


//        $where = 'is_delete=0 and order_status !=3 and  user_id='.$this->user_id;
        if(I('status_id')==1) {//待付款

            $where['pay_status']=0;
            $where['order_status']=0;

//            $where.=' and pay_status =0 ';
        }elseif(I('status_id')==2){//正在交易
            $where['pay_status']=1;
            $where['order_status']=1;
//            $where.=' and pay_status =1 and order_status=1 ';
        }elseif(I('status_id')==3){//交易完成
            $where['pay_status']=1;
            $where['order_status']=6;
//            $where.=' and pay_status =1 and order_status=6 ';
        }elseif(I('status_id')==4){//退款中
            $where['pay_status']=1;
            $where['order_status']=2;
//            $where.=' and pay_status =1 and order_status=2 ';
        }

    /*    //条件搜索
       if(I('get.type')){
           $where .= C(strtoupper(I('get.type')));
       }

       // 搜索订单 根据商品名称 或者 订单编号
       $search_key = trim(I('search_key'));       
       if($search_key)
       {
          $where .= "  and (order_sn like '%$search_key%' or order_id in (select order_id from `".C('DB_PREFIX')."order_goods` where goods_name like '%$search_key%') )  ";
       }*/
        $count = M('order1')->where($where)->count();
        $Page = new Page($count,10);
        $show = $Page->show();
        $order_str = "order_id DESC";
        $order_list = M('order1')->order($order_str)->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();



        //获取订单商品
        foreach($order_list as $k=>$v)
        {

            $v['button']=$this->getOrderButton($v);
            $where_1['order_id']=$v['order_id'];

            $return_order = M('return_order')->where($where_1)->find();

            if($return_order){
                $v['is_return']  =$return_order['status'];
                if($return_order['status']==2){
                    $v['return_info']  =$return_order['remark'];
                }
            }

            $goods_id=$v['goods_id'];
            $v['goods']=M('goods')->where("goods_id=$goods_id")->find();
            $order_list[$k]=$v;
        }



        $this->assign('order_status',C('ORDER_STATUS'));
        $this->assign('shipping_status',C('SHIPPING_STATUS'));
        $this->assign('pay_status',C('PAY_STATUS'));
        $this->assign('page',$show);
        $this->assign('lists',$order_list);
        $this->assign('active','order_list');
        $this->assign('active_status',I('get.type'));
        $this->display();
    }

    public function getOrderButton($order){

        $os = $order['order_status'];//订单状态
        $ps = $order['pay_status'];//支付状态
        $btn = array();

        if($ps==0){//待支付
            $btn['pay'] = '付款';
            $btn['cancel'] = '取消';
        }else{
            if($os==1){//已支付
                //判断订单是否可申请退款
                if($order['pay_time']>0){
                    $day= (time()-$order['pay_time'])/86400;
                    if($day<7){
                        $btn['refund'] = '申请退款';
                    }
                }
            }elseif($os==2){//已申请退款
            }elseif($os==3){//3=取消
                $btn['delete'] = '删除';
            }elseif($os==4){//4=该店铺被别人购买
                $btn['delete'] = '删除';
            }elseif($os==5){//5=已退款
                $btn['delete'] = '删除';
            }elseif($os==6){// 6=已完成
                $btn['delete'] = '删除';
            }elseif($os==7){// 7=买家违约
                $btn['delete'] = '删除';
            }
        }
        return $btn;
    }




    /**
     *删除订单
     */
    public function delete_order(){
        $order_id=I('order_id');
        $order =M('order1')->where("order_id=$order_id")->find();
        if(!$order){
            $this->error('没有获取到订单信息');
            exit;
        }



        if($order['order_status']==1){
            $this->error('该订单不能删除');
            exit;
        }
        $return_order=M('return_order')->where("order_id=$order_id")->find();
        if($order['order_status']==2&&$return_order['status']=='0'){
            $this->error('该订单不能删除');
            exit;
        }

        //删除订单时，更改状态未已删除即可，不删除订单本身

        $up_data['order_id']=$order_id;
        $up_data['is_delete']=1;
        $res=M('order1')->save($up_data);




//        $res=M('order1')->where("order_id=$order_id")->delete();






        /*if($return_order)
            M('return_order')->where("order_id=$order_id")->delete();//删除退款信息*/
        if($res){
            $this->success('删除成功',U('order_list'));
        }else{
            $this->error('删除失败，请重新尝试！',U('order_list'));
        }
    }


    /**
     *上传转账凭证
     */
    public function transfer_vouchers(){
        $order_id=I('order_id');
        $order =M('order1')->where("order_id=$order_id")->find();
        if(!$order){
            $this->error('没有获取到订单信息');
            exit;
        }
        //用户余额
        $res=M('order1')->save(I());
        if($res){
            $this->success('提交成功，客服人员将尽快处理您的订单！',U('order_detail',array('id'=>$order_id)));
        }else{
            $this->error('提交失败，请重新尝试！',U('order_detail',array('id'=>$order_id)));
        }


    }

    /**
     * 支付
     */

    public function order_pay1(){
        $order_id=I('order_id');
        $order =M('order1')->where("order_id=$order_id")->find();
        if(!$order){
            $this->error('没有获取到订单信息');
            exit;
        }
        $g_where['goods_id']=$order['goods_id'];
        $goods_status=M('goods')->where($g_where)->getField('status');
        if($goods_status==0){
            $this->error('该商品已下架，如想咨询该店铺情况，请于业务员联系！');
            exit;
        }
        if($goods_status==3||$goods_status==4){
            M('order1')->where("order_id=$order_id")->save(array('status'=>4));//修改状态为  4=被她人购买
            $this->error('该商品已被人购买，正在处理过户事宜。请知悉！');
            exit;
        }
        //用户余额
        $user_money=M('users')->where("user_id=$this->user_id")->getField('user_money');
        if($order['pay_price']>$user_money){
            $this->error('余额不足，请充值！',U('User/my_money'));
            exit;
        }
        //扣减余额
        $up_data['user_id'] =$this->user_id;
        $up_data['user_money'] =$user_money-$order['pay_price'];
        $res =M('users')->save($up_data);
        if($res){
            //支付后 改变订单状态
            update_pay_status($order['order_sn']);
            $this->success('支付成功',U('order_detail',array('order_id'=>$order_id)));
        }else{
            $this->error('支付成功，请重新尝试！',U('order_detail',array('order_id'=>$order_id)));
        }
    }


    /**
     * 订单详情
     */
    public function order_detail(){
        $id = I('get.id');
        $map['order_id'] = $id;
        $map['user_id'] = $this->user_id;
        $order_info = M('order1')->where($map)->find();
        $goods_id =$order_info['goods_id'];
        $goods = M('goods')->where("goods_id=$goods_id")->find();
        if(!$order_info){
            $this->error('没有获取到订单信息');
            exit;
        }
        $user_money=M('users')->where("user_id=$this->user_id")->getField('user_money');
        if($order_info['pay_price']>$user_money)
            $this->assign('no_money',1);
        $this->assign('order',$order_info);
        $this->assign('goods_type',$goods['goods_type']);
        $this->assign('user_money',$user_money);
        $this->display();

    }

    /**
     * 取消订单
     */
    public function cancel_order(){
        $id = I('get.id');
        //检查是否有积分，余额支付
        $logic = new UsersLogic();
        $data = $logic->cancel_order($this->user_id,$id);
        if($data['status'] < 0)
            $this->error($data['msg']);
        $this->success($data['msg']);
    }

    /**
     * 用户地址列表
     */
    public function address_list(){
        $address_lists = get_user_address_list($this->user_id);
        $region_list = get_region_list();
        $this->assign('region_list',$region_list);
        $this->assign('lists',$address_lists);
        $this->assign('active','address_list');

        $this->display();
    }
    /*
     * 添加地址
     */
    public function add_address(){
        header("Content-type:text/html;charset=utf-8");

        if(IS_POST){
            $logic = new UsersLogic();
            $data = $logic->add_address($this->user_id,0,I('post.'));
            if($data['status'] != 1)
                exit('<script>alert("'.$data['msg'].'");history.go(-1);</script>');
            $call_back = $_REQUEST['call_back'];
            echo "<script>parent.{$call_back}('success');</script>";
            exit(); // 成功 回调closeWindow方法 并返回新增的id
        }
        $p = M('region')->where(array('parent_id'=>0,'level'=> 1))->select();
        $this->assign('province',$p);
        $this->display('edit_address');

    }

    /*
     * 地址编辑
     */
    public function edit_address(){
        header("Content-type:text/html;charset=utf-8");
        $id = I('get.id');
        $address = M('user_address')->where(array('address_id'=>$id,'user_id'=> $this->user_id))->find();
        if(IS_POST){
            $logic = new UsersLogic();
            $data = $logic->add_address($this->user_id,$id,I('post.'));
            if($data['status'] != 1)
                exit('<script>alert("'.$data['msg'].'");history.go(-1);</script>');

            $call_back = $_REQUEST['call_back'];
            echo "<script>parent.{$call_back}('success');</script>";
            exit(); // 成功 回调closeWindow方法 并返回新增的id
        }
        //获取省份
        $p = M('region')->where(array('parent_id'=>0,'level'=> 1))->select();
        $c = M('region')->where(array('parent_id'=>$address['province'],'level'=> 2))->select();
        $d = M('region')->where(array('parent_id'=>$address['city'],'level'=> 3))->select();
        if($address['twon']){
        	$e = M('region')->where(array('parent_id'=>$address['district'],'level'=>4))->select();
        	$this->assign('twon',$e);
        }

        $this->assign('province',$p);
        $this->assign('city',$c);
        $this->assign('district',$d);
        $this->assign('address',$address);
        $this->display();
    }

    /*
     * 设置默认收货地址
     */
    public function set_default(){
        $id = I('get.id');
        M('user_address')->where(array('user_id'=>$this->user_id))->save(array('is_default'=>0));
        $row = M('user_address')->where(array('user_id'=>$this->user_id,'address_id'=>$id))->save(array('is_default'=>1));
        if(!$row)
            $this->error('操作失败');
        $this->success("操作成功");
    }

    /*
     * 地址删除
     */
    public function del_address(){
        $id = I('get.id');

        $address = M('user_address')->where("address_id = $id")->find();
        $row = M('user_address')->where(array('user_id'=>$this->user_id,'address_id'=>$id))->delete();
        // 如果删除的是默认收货地址 则要把第一个地址设置为默认收货地址
        if($address['is_default'] == 1)
        {
            $address2 = M('user_address')->where("user_id = {$this->user_id}")->find();
            $address2 && M('user_address')->where("address_id = {$address2['address_id']}")->save(array('is_default'=>1));
        }
        if(!$row)
            $this->error('操作失败',U('User/address_list'));
        else
            $this->success("操作成功",U('User/address_list'));
    }


    public function save_pickup()
    {
        $post = I('post.');
        if (empty($post['consignee'])) {
            return array('status' => -1, 'msg' => '收货人不能为空', 'result' => '');
        }
        if (!$post['province'] || !$post['city'] || !$post['district']) {
            return array('status' => -1, 'msg' => '所在地区不能为空', 'result' => '');
        }
        if(!check_mobile($post['mobile'])){
            return array('status'=>-1,'msg'=>'手机号码格式有误','result'=>'');
        }
        if(!$post['pickup_id']){
            return array('status'=>-1,'msg'=>'请选择自提点','result'=>'');
        }

        $user_logic = new UsersLogic();
        $res = $user_logic->add_pick_up($this->user_id, $post);
        if($res['status'] != 1){
            exit('<script>alert("'.$res['msg'].'");history.go(-1);</script>');
        }
        $call_back = $_REQUEST['call_back'];
        echo "<script>parent.{$call_back}({$post['province']},{$post['city']},{$post['district']});</script>";
        exit(); // 成功 回调closeWindow方法 并返回新增的id
    }

    /*
     * 评论晒单
     */
    public function comment(){
        $user_id = $this->user_id;
        $status = I('get.status',-1);
        $logic = new UsersLogic();
        $data = $logic->get_comment($user_id,$status); //获取评论列表
        $this->assign('page',$data['show']);// 赋值分页输出
        $this->assign('comment_list',$data['result']);
        $this->assign('active','comment');
        $this->display();
    }

    /*
     *添加评论
     */
    public function add_comment()
    {
            $user_info = session('user');
            $comment_img = serialize(I('comment_img')); // 上传的图片文件
            $add['goods_id'] = I('goods_id');
            $add['email'] = $user_info['email'];
            //$add['nick'] = $user_info['nickname'];
            $add['username'] = $user_info['nickname'];
            $add['order_id'] = I('order_id');
            $add['service_rank'] = I('service_rank');
            $add['deliver_rank'] = I('deliver_rank');
            $add['goods_rank'] = I('goods_rank');
            //$add['content'] = htmlspecialchars(I('post.content'));
            $add['content'] = I('content');
            $add['img'] = $comment_img;
            $add['add_time'] = time();
            $add['ip_address'] = $_SERVER['REMOTE_ADDR'];
            $add['user_id'] = $this->user_id;
            $logic = new UsersLogic();
            //添加评论
            $row = $logic->add_comment($add);
            exit(json_encode($row));
    }

    /*
     * 个人信息
     */
    public function info(){
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); // 获取用户信息
        $user_info = $user_info['result'];
        if(IS_POST){
            I('post.nickname') ? $post['nickname'] = I('post.nickname') : false; //昵称
            I('post.qq') ? $post['qq'] = I('post.qq') : false;  //QQ号码
            I('post.head_pic') ? $post['head_pic'] = I('post.head_pic') : false; //头像地址
            I('post.sex') ? $post['sex'] = I('post.sex') : false;  // 性别
            I('post.birthday') ? $post['birthday'] = strtotime(I('post.birthday')) : false;  // 生日
            I('post.province') ? $post['province'] = I('post.province') : false;  //省份
            I('post.city') ? $post['city'] = I('post.city') : false;  // 城市
            I('post.district') ? $post['district'] = I('post.district') : false;  //地区
            if(!$userLogic->update_info($this->user_id,$post))
                $this->error("保存失败");
            $this->success("操作成功");
            exit;
        }
        //  获取省份
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        //  获取订单城市
        $city =  M('region')->where(array('parent_id'=>$user_info['province'],'level'=>2))->select();
        //获取订单地区
        $area =  M('region')->where(array('parent_id'=>$user_info['city'],'level'=>3))->select();

        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('area',$area);
        $this->assign('user',$user_info);
        $this->assign('sex',C('SEX'));
        $this->assign('active','info');
        $this->display();
    }

    /*
     * 邮箱验证
     */
    public function email_validate(){
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); // 获取用户信息
        $user_info = $user_info['result'];
        $step = I('get.step',1);
        if(IS_POST){
            $email = I('post.email');
            $old_email = I('post.old_email',''); //旧邮箱
            $code = I('post.code');
            $info = session('validate_code');
            if(!$info)
                $this->error('非法操作');
            if($info['time']<time()){
            	session('validate_code',null);
            	$this->error('验证超时，请重新验证');
            }
            //检查原邮箱是否正确
            if($user_info['email_validated'] == 1 && $old_email != $user_info['email'])
                $this->error('原邮箱匹配错误');
            //验证邮箱和验证码
            if($info['sender'] == $email && $info['code'] == $code){
                session('validate_code',null);
                if(!$userLogic->update_email_mobile($email,$this->user_id))
                    $this->error('邮箱已存在');
                $this->success('绑定成功',U('Home/User/index'));
                exit;
            }
            $this->error('邮箱验证码不匹配');
        }
        $this->assign('user_info',$user_info);
        $this->assign('step',$step);
        $this->display();
    }






    /*
    * 手机验证
    */
    public function mobile_validate(){
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); //获取用户信息
        $user_info = $user_info['result'];
        $config = F('sms','',TEMP_PATH);
        $sms_time_out = $config['sms_time_out'];
        $step = I('get.step',1);
        if(IS_POST){
            $mobile = I('post.mobile');
            $old_mobile = I('post.old_mobile','');
            $code = I('post.code');
            $info = session('validate_code');
            if(!$info)
                $this->error('非法操作');
            if($info['time']<time()){
            	session('validate_code',null);
            	$this->error('验证超时，请重新验证');
            }
            //检查原手机是否正确
            if($user_info['mobile_validated'] == 1 && $old_mobile != $user_info['mobile'])
                $this->error('原手机号码错误');
            //验证手机和验证码
            if($info['sender'] == $mobile && $info['code'] == $code){
                session('validate_code',null);
                //验证有效期
                if($info['time'] < time())
                    $this->error('验证码已失效');
                if(!$userLogic->update_email_mobile($mobile,$this->user_id,2))
                    $this->error('手机已存在');
                $this->success('绑定成功',U('Home/User/index'));
                exit;
            }
            $this->error('手机验证码不匹配');
        }

        //超时时间
		$this->assign('regis_sms_enable',tpCache('sms.regis_sms_enable')); // 注册启用短信：
        $this->assign('regis_smtp_enable',tpCache('smtp.regis_smtp_enable')); // 注册启用邮箱：
        $sms_time_out = tpCache('sms.sms_time_out')>0 ? tpCache('sms.sms_time_out') : 60;
        $this->assign('sms_time_out', $sms_time_out); // 手机短信超时时间
		
        $validate_code = session('validate_code');
		$send_time=$validate_code['time'];
        $stime=$send_time-time();
        $stime>0?$stime=$stime:$stime=0;
        $this->assign('stime', $stime); //  刷新页面后还有多长时间
		
        $this->assign('user_info',$user_info);
        $this->assign('time',$sms_time_out);
        $this->assign('step',$step);
        $this->display();
    }


    public function send_sms_code(){
        $send=I('send');
        $type = I('type');


        $code = get_sms_code(4);
        if($type==1){//手机验证码
            $sender=$mobile=$send;
            $sms=A('Sms');
            $send=$sms->sms_test($mobile,$code);
        }elseif($type==2){//邮箱验证
            $sender= $send;
            $res=send_email($sender,'验证码','您好，你的验证码是：'.$code);
        }
        if($send['status'] != 1||!$res)
            exit(json_encode(array('status'=>-1,'msg'=>$send['msg'])));
        $sms_time_out = tpCache('sms.sms_time_out');
        $sms_time_out = $sms_time_out ? $sms_time_out : 60;
        $info['code'] = $code;
        $info['sender'] = $sender;
        $check['is_check'] = 0;
        $info['time'] = time() + $sms_time_out; //有效验证时间
        session('validate_code',$info);
        $res = array('status'=>1,'msg'=>'验证码已发送，请注意查收');
        exit(json_encode(array('status'=>1,'msg'=>'验证码已发送，请注意查收')));
    }





    /**
     * 发送手机注册验证码
     */
    public function send_sms_reg_code(){
        $type=I('type');
        $mobile = I('mobile');
        $email = I('email');
        if(!$type){
            $u_where['mobile']=$mobile;
            $count=M('users')->where($u_where)->count();
            if($count)
                exit(json_encode(array('status'=>-2,'msg'=>' 该手机号已被注册，请更换')));
        }
        $code = get_sms_code(4);

        if($type=='email'){
            //邮件发送功能待开发
            dump('功能待开发');exit;
            $sender= $email;
            $res=send_email($sender,'验证码','您好，你的验证码是：'.$code);


            if(!$res)
                exit(json_encode(array('status'=>-1,'msg'=>'发送失败，请重试')));
        }else{

            $sender= $mobile;
            $sms=A('Sms');
            $send=$sms->sms_test($sender,$code);
            if($send['status'] != 1)
                exit(json_encode(array('status'=>-1,'msg'=>$send['msg'])));
        }

        $sms_time_out = tpCache('sms.sms_time_out');
        $sms_time_out = $sms_time_out ? $sms_time_out : 60;
        $info['code'] = $code;
        $info['sender'] = $sender;
        $check['is_check'] = 0;
        $info['time'] = time() + $sms_time_out; //有效验证时间
        session('validate_code',$info);
        $res = array('status'=>1,'msg'=>'验证码已发送，请注意查收');
		exit(json_encode(array('status'=>1,'msg'=>'验证码已发送，请注意查收')));

    }





    /*
     *商品收藏
     */
    public function goods_collect(){
        $userLogic = new UsersLogic();
        $data = $userLogic->get_goods_collect($this->user_id);
        foreach($data['result'] AS $k=>$v){
            $where['goods_id']=$v['goods_id'];
            $v['goods']=M('goods')->where($where)->find();
            $data['result'][$k]=$v;
        }
        $this->assign('page',$data['show']);// 赋值分页输出
        $this->assign('lists',$data['result']);
        $this->assign('active','goods_collect');
        $this->display();
    }

    /*
     * 删除一个收藏商品
     */
    public function del_goods_collect(){
        $id = I('get.id');

        if(!$id)
            $this->error("缺少ID参数");
        $row = M('goods_collect')->where(array('collect_id'=>$id,'user_id'=>$this->user_id))->delete();
        if(!$row)
            $this->error("删除失败");
        $this->success('删除成功');
    }

    /*
     * 密码修改
     */
    public function password(){
        //检查是否第三方登录用户
        $logic = new UsersLogic();
        $data = $logic->get_info($this->user_id);
        $user = $data['result'];
        if($user['mobile'] == ''&& $user['email'] == '')
            $this->error('请先绑定手机或邮箱',U('Home/User/info'));
        if(IS_POST){
            $userLogic = new UsersLogic();
            $data = $userLogic->password($this->user_id,I('post.old_password'),I('post.new_password'),I('post.confirm_password')); // 获取用户信息
            if($data['status'] == -1)
                $this->error($data['msg']);
            $this->success($data['msg']);
            exit;
        }
        $this->display();
    }

    public function forget_pwd(){
    	if($this->user_id > 0){
    		header("Location: ".U('Home/User/index'));
    	}
    	if(IS_POST){
    		$logic = new UsersLogic();
    		$username = I('post.username');
    		$code = I('post.code');
    		$new_password = I('post.new_password');
    		$confirm_password = I('post.confirm_password');
    		$pass = false;

    		//检查是否手机找回
    		if(check_mobile($username)){
    			if(!$user = get_user_info($username,2))
    				$this->error('账号不存在');
    			$check_code = $logic->sms_code_verify($username,$code,$this->session_id);
    			if($check_code['status'] != 1)
    				$this->error($check_code['msg']);
    			$pass = true;
    		}
    		//检查是否邮箱
    		if(check_email($username)){
    			if(!$user = get_user_info($username,1))
    				$this->error('账号不存在');
    			$check = session('forget_code');
    			if(empty($check))
    				$this->error('非法操作');
    			if(!$username || !$code || $check['email'] != $username || $check['code'] != $code)
    				$this->error('邮箱验证码不匹配');
    			$pass = true;
    		}
    		if($user['user_id'] > 0 && $pass)
    			$data = $logic->password($user['user_id'],'',$new_password,$confirm_password,false); // 获取用户信息
    		if($data['status'] != 1)
    			$this->error($data['msg'] ? $data['msg'] :  '操作失败');
    		$this->success($data['msg'],U('Home/User/login'));
    		exit;
    	}
        $this->display();
    }

    public function set_pwd(){
    	if($this->user_id > 0){
    		header("Location: ".U('Home/User/index'));
    	}
    	$check = session('validate_code');
    	if(empty($check)){
    		header("Location:".U('Home/User/forget_pwd'));
    	}elseif($check['is_check']==0){
    		$this->error('验证码还未验证通过',U('Home/User/forget_pwd'));
    	}
    	if(IS_POST){
    		$password = I('post.password');
    		$password2 = I('post.password2');
    		if($password2 != $password){
    			$this->error('两次密码不一致',U('Home/User/forget_pwd'));
    		}
    		if($check['is_check']==1){
    			//$user = get_user_info($check['sender'],1);
                $user = M('users')->where("mobile = '{$check['sender']}' or email = '{$check['sender']}'")->find();
    			M('users')->where("user_id=".$user['user_id'])->save(array('password'=>encrypt($password)));
    			session('validate_code',null);
    			header("Location:".U('Home/User/finished'));
    		}else{
    			$this->error('验证码还未验证通过',U('Home/User/forget_pwd'));
    		}
    	}
    	$this->display();
    }

    public function finished(){
    	if($this->user_id > 0){
    		header("Location: ".U('Home/User/index'));
    	}
    	$this->display();
    }

    public function check_captcha(){
    	$verify = new Verify();
    	$type = I('post.type','user_login');
    	if (!$verify->check(I('post.verify_code'), $type)) {
    		exit(json_encode(0));
    	}else{
    		exit(json_encode(1));
    	}
    }

    public function check_username(){
    	$username = I('post.username');
    	if(!empty($username)){
    		$count = M('users')->where("email='$username' or mobile='$username'")->count();
    		exit(json_encode(intval($count)));
    	}else{
    		exit(json_encode(0));
    	}
    }

    public function identity(){
    	if($this->user_id > 0){
    		header("Location: ".U('Home/User/index'));
    	}
    	$username = I('post.username');
    	$userinfo = array();
    	if($username){
    		$userinfo = M('users')->where("email='$username' or mobile='$username'")->find();
    		$userinfo['username'] = $username;
    		session('userinfo',$userinfo);
    	}else{
    		$this->error('参数有误！！！');
    	}
    	if(empty($userinfo)){
    		$this->error('非法请求！！！');
    	}
    	unset($userinfo['password']);


        $validate_code = session('validate_code');
        $send_time=$validate_code['time'];
        $stime=$send_time-time();
        $stime>0?$stime=$stime:$stime=0;
        $this->assign('stime', $stime); //  刷新页面后还有多长时间


        $sms_time_out = tpCache('sms.sms_time_out')>0 ? tpCache('sms.sms_time_out') : 60;
        $this->assign('sms_time_out', $sms_time_out); // 手机短信超时时间



        strpos($username,'@')?$v_type1='email':$v_type1='phone';

    	$this->assign('v_type1',$v_type1);
    	$this->assign('userinfo',$userinfo);
    	$this->display();
    }

    //发送验证码
    public function send_validate_code(){



    	$type = I('type');
    	$send = I('send');


    	$logic = new UsersLogic();
    	$res = $logic->send_validate_code($send, $type);
        $this->ajaxReturn($res);
    }

    public function check_validate_code(){
    	$code = I('post.code');
    	$send = I('send');
    	$logic = new UsersLogic();
    	$res = $logic->check_validate_code($code, $send);
        $this->ajaxReturn($res);
    }

    /**
     * 验证码验证
     * $id 验证码标示
     */
    private function verifyHandle($id)
    {
        $verify = new Verify();
        if (!$verify->check(I('post.verify_code'), $id ? $id : 'user_login')) {
            $this->error("验证码错误");
        }
    }

    /**
     * 验证码获取
     */
    public function verify()
    {
        //验证码类型
        $type = I('get.type') ? I('get.type') : 'user_login';
        $config = array(
			'imageW'    =>    105,
            'imageH'    =>    52,
            'length' => 4,
            'useCurve' => false,
            'useNoise' => false,
			'bg'  => array(0, 0, 0),
        );
        $Verify = new Verify($config);
        $Verify->entry($type);
    }

    public function order_confirm(){
        $id = I('get.id',0);

        $data = confirm_order($id,$this->user_id);
        if(!$data['status'])
            $this->error($data['msg']);
	else
	   $this->success($data['msg']);
    }

    /**
     * 申请退款
     */
    public function return_order()
    {
        $order_id = I('order_id',0);
        $order = M('order1')->where("order_id = $order_id and user_id = {$this->user_id}")->find();
        if(!$order||$order['order_status']!=1)
        {
            $this->error('非法操作');
            exit;
        }


        $return_order = M('return_order')->where("order_id = $order_id")->find();
        if(!empty($return_order))
        {
            $this->success('已经提交过退货申请!', $_SERVER['HTTP_REFERER']);
            exit;
        }
        if(IS_POST)
        {
            $data['order_id'] = $order_id;
            $data['order_sn'] = $order['order_sn'];
            $data['addtime'] = time();
            $data['user_id'] = $this->user_id;
            $data['yuanyin'] =I('yuanyin');
            $data['reason'] = I('reason'); // 问题描述

            $res= M('return_order')->add($data);


            $up_data['order_id']=$order_id;
            $up_data['order_status']=2;
             M('order1')->save($up_data);

            //写入日志
            logOrder($order_id,I('reason'),'申请退款',$this->user_id);
            $config = tpCache('shop_info');
            if($config['admin_email']){
                $to=$config['admin_email'];
                $title='申请退款通知';
                $content=get_email_content_return($res);
                new_send_email($to,$title,$content);

            }
            $this->success('申请成功,客服第一时间会帮你处理',U('Home/User/order_list'));
            exit;
        }

        $goods = M('order_goods')->where("order_id = $order_id")->select();
        $this->assign('goods',$goods);
        $this->assign('order_id',$order_id);
        $this->display();
    }

    /**
     * 申请退货
     */
    public function return_goods()
    {
        $order_id = I('order_id',0);
        $order_sn = I('order_sn',0);
        $goods_id = I('goods_id',0);
	$spec_key = I('spec_key');
        
        $c = M('order')->where("order_id = $order_id and user_id = {$this->user_id}")->count();
        if($c == 0)
        {
            $this->error('非法操作');
            exit;
        }         
        
        $return_goods = M('return_goods')->where("order_id = $order_id and goods_id = $goods_id and spec_key = '$spec_key'")->find();            
        if(!empty($return_goods))
        {
            $this->success('已经提交过退货申请!',U('Home/User/return_goods_info',array('id'=>$return_goods['id'])));
            exit;
        }       
        if(IS_POST)
        {
            $data['order_id'] = $order_id; 
            $data['order_sn'] = $order_sn; 
            $data['goods_id'] = $goods_id; 
            $data['addtime'] = time(); 
            $data['user_id'] = $this->user_id;            
            $data['type'] = I('type'); // 服务类型  退货 或者 换货
            $data['reason'] = I('reason'); // 问题描述
            $data['imgs'] = I('imgs'); // 用户拍照的相片
            $data['spec_key'] = I('spec_key'); // 商品规格			
            M('return_goods')->add($data);            
            $this->success('申请成功,客服第一时间会帮你处理',U('Home/User/order_list'));
            exit;
        }
               
        $goods = M('goods')->where("goods_id = $goods_id")->find();        
        $this->assign('goods',$goods);
        $this->assign('order_id',$order_id);
        $this->assign('order_sn',$order_sn);
        $this->assign('goods_id',$goods_id);
        $this->display();
    }
    
    /**
     * 退换货列表
     */
    public function return_goods_list()
    {        
        $count = M('return_goods')->where("user_id = {$this->user_id}")->count();
        $page = new Page($count,10);
        $list = M('return_goods')->where("user_id = {$this->user_id}")->order("id desc")->limit("{$page->firstRow},{$page->listRows}")->select();
        $goods_id_arr = get_arr_column($list, 'goods_id');
        if(!empty($goods_id_arr))
            $goodsList = M('goods')->where("goods_id in (".  implode(',',$goods_id_arr).")")->getField('goods_id,goods_name');        
        $this->assign('goodsList', $goodsList);
        $this->assign('list', $list);
        $this->assign('page', $page->show());// 赋值分页输出
        $this->display();
    }
    
    /**
     *  退货详情
     */
    public function return_goods_info()
    {
        $id = I('id',0);
        $return_goods = M('return_goods')->where("id = $id")->find();
        if($return_goods['imgs'])
            $return_goods['imgs'] = explode(',', $return_goods['imgs']);        
        $goods = M('goods')->where("goods_id = {$return_goods['goods_id']} ")->find();                
        $this->assign('goods',$goods);
        $this->assign('return_goods',$return_goods);
        $this->display();
    }
    
    /**
     * 安全设置
     */
    public function safety_settings()
    {
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); // 获取用户信息
        $user_info = $user_info['result'];        
        $this->assign('user',$user_info);
        $this->display();      
    }
    
    /**
     * 申请提现记录
     */
    public function withdrawals(){
        
    	//C('TOKEN_ON',true);
    	if(IS_POST)
    	{
            $this->verifyHandle('withdrawals');                
    		$data = I('post.');
    		$data['user_id'] = $this->user_id;    		    		
    		$data['create_time'] = time();                
                $distribut_min = tpCache('distribut.min'); // 最少提现额度
                if($data['money'] < $distribut_min)
                {
                        $this->error('每次最少提现额度'.$distribut_min);
                        exit;
                }
                if($data['money'] > $this->user['user_money'])
                {
                        $this->error("你最多可提现{$this->user['user_money']}账户余额.");
                        exit;
                }     
                 
    		if(M('withdrawals')->add($data)){
    			$this->success("已提交申请");
                        exit;
    		}else{
    			$this->error('提交失败,联系客服!');
                        exit;
    		}
    	}
        
        $where = " user_id = {$this->user_id}";        
        $count = M('withdrawals')->where($where)->count();
        $page = new Page($count,10);
        $show = $page->show();
        $list = M('withdrawals')->where($where)->order("id desc")->limit("{$page->firstRow},{$page->listRows}")->select();   
        $this->assign('show',$show);// 赋值分页输出
        $this->assign('list',$list); // 下线      
        $this->display(); 
    }
    
   public  function recharge(){
   		if(IS_POST){
   			$user = session('user');
   			$data['user_id'] = $this->user_id;
   			$data['nickname'] = $user['nickname'];
   			$data['account'] = I('account');
   			$data['order_sn'] = 'recharge'.get_rand_str(10,0,1);
   			$data['ctime'] = time();
   			$order_id = M('recharge')->add($data);
   			if($order_id){
   				$url = U('Payment/getPay',array('pay_radio'=>$_REQUEST['pay_radio'],'order_id'=>$order_id));
   				redirect($url);
   			}else{
   				$this->error('提交失败,参数有误!');
   			}
   		}
   		
	   	$paymentList = M('Plugin')->where("`type`='payment' and code!='cod' and status = 1 and  scene in(0,2)")->select();
	   	$paymentList = convert_arr_key($paymentList, 'code');	   	
	   	foreach($paymentList as $key => $val)
	   	{
	   		$val['config_value'] = unserialize($val['config_value']);
	   		if($val['config_value']['is_bank'] == 2)
	   		{
	   			$bankCodeList[$val['code']] = unserialize($val['bank_code']);
	   		}
	   	}
	   	$bank_img = include 'Application/Home/Conf/bank.php'; // 银行对应图片
	   	$this->assign('paymentList',$paymentList);
	   	$this->assign('bank_img',$bank_img);
	   	$this->assign('bankCodeList',$bankCodeList);
	   	
	   	$count = M('recharge')->where(array('user_id'=>$this->user_id))->count();
	   	$Page = new Page($count,10);
	   	$show = $Page->show();
	   	$recharge_list = M('recharge')->where(array('user_id'=>$this->user_id))->limit($Page->firstRow.','.$Page->listRows)->select();
	   	$this->assign('page',$show);
	   	$this->assign('recharge_list',$recharge_list);//充值记录
	   	
	   	$count2 = M('account_log')->where(array('user_id'=>$this->user_id,'user_money'=>array('gt',0)))->count();
	   	$Page2 = new Page($count2,10);
	   	$consume_list = M('account_log')->where(array('user_id'=>$this->user_id,'user_money'=>array('gt',0)))->limit($Page2->firstRow.','.$Page2->listRows)->select();
	   	$this->assign('consume_list',$consume_list);//消费记录
	   	$this->assign('page2',$Page2->show());
   		$this->display();
   } 

    /**
     *  用户消息通知
     * @author dyr
     * @time 2016/09/01
     */
    public function message_notice()
    {
        $this->display();
    }
    /**
     * ajax用户消息通知请求
     * @author dyr
     * @time 2016/09/01
     */
    public function ajax_message_notice()
    {
        $type = I('type',0);
        $user_logic = new UsersLogic();
        if ($type == 1) {
            //系统消息
            $user_sys_message = D('Message')->getUserMessageNotice();
            $user_logic->setSysMessageForRead();
        } else if ($type == 2) {
            //活动消息：后续开发
            $user_sys_message = array();
        } else {
            //全部消息：后续完善
            $user_sys_message = D('Message')->getUserMessageNotice();
        }
        $this->assign('messages', $user_sys_message);
        $this->display();
    }
	
	/*********资金管理*********/
	
	/*我要充值*/
	public function money_add()
    {
		$this->display();
	}
	
	/*充值记录*/
	public function money_addjl()
    {
        $where['user_id']=$_SESSION['user']['user_id'];
        $log_list =M('account_log')->where($where)->select();
        $this->assign('lists',$log_list);
		$this->display();
	}
	
	/*我要提现*/
	public function money_cash()
    {
		$this->display();
	}
	
	/*提现记录*/
	public function money_cashjl()
    {
		$this->display();
	}
	
	/*收支明细*/
	public function money_payments()
    {
		$this->display();
	}
	
	/*冻结明细*/
	public function money_frozen()
    {
		$this->display();
	}
	
	/*********资金管理*********/

    /*********我的投诉*********/
	
    /**
     * 投诉列表
     */
    public function my_complain()
    {
        $where['user_id']=$_SESSION['user']['user_id'];
        $count = M('complain')->where($where)->count();
        $Page = new Page($count,10);
        $show = $Page->show();
        $complain_list = M('complain')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('page',$show);
        $this->assign('lists',$complain_list);
        $this->display();
    }
    /**
     * 投诉详情
     */
	public function my_complain_detail()
    {
        $id=I('id');
        $where['id']=$id;
        $info = M('complain')->where($where)->find();
        $lists=M('complain_reply')->where("c_id=$id")->oeder('add_time ASC')->select();
        $this->assign('lists',$lists);
        $this->assign('info',$info);
        $this->display();
    }


    public function c_reply(){
        $re_data['content']=I('content');
        $re_data['c_id']=I('id');
        $re_data['user_id']=$_SESSION['user']['user_id'];
        $re_data['add_time']=time();
        $res =M('complain_reply')->add($re_data);
        if($res){
            $this->success('提交成功!',U('my_complain_detail',array('id'=>I('id'))));
        }else{
            $this->error('提交失败，请重试!',U('my_complain_detail',array('id'=>I('id'))));
        }
    }

    /**
     * 删除投诉
     */
    public function delete_complain(){
        $id=I('id');

        $res=M('complain')->where("id=$id")->delete();
        if($res){
            $this->success('删除成功',U('my_complain'));
        }else{
            $this->error('删除失败，请重新尝试！',U('my_complain'));
        }
    }
    /*********我的求购*********/

    /**
     *  需求列表
     */

    public function my_ask_buy(){

        if(I('status_id')==1) {//待付款
            $where['status']=0;
        }elseif(I('status_id')==2){//正在交易
            $where['status']=1;
        }


        $where['user_id']=$_SESSION['user']['user_id'];
        $count = M('ask_buy')->where($where)->count();
        $Page = new Page($count,10);
        $show = $Page->show();
        $list = M('ask_buy')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('page',$show);
        $this->assign('lists',$list);
        $this->display();
    }



    /**
     *  需求详情
     */

	public function my_ask_buy_detail(){
        $where['id']=I('id');
        $info = M('ask_buy')->where($where)->find();
        $this->assign('info',$info);
        $this->display();
    }

    /**
     * 删除需求
     */
    public function delete_ask_buy(){
        $id=I('id');
        $res=M('ask_buy')->where("id=$id")->delete();
        if($res){
            $this->success('删除成功',U('my_ask_buy'));
        }else{
            $this->error('删除失败，请重新尝试！',U('my_ask_buy'));
        }
    }


    public function binding(){

        if(IS_POST){
            //验证账号密码
            $username = I('post.username');
            $password = I('post.password');
            $username = trim($username);
            $password = trim($password);
            $logic = new UsersLogic();
            $res = $logic->login($username,$password);
            if($res['status']==1){
                //更新会员信息
                $o_user=$res['result'];
                $o_user_id=$o_user['user_id'];
                $n_user_id=$_SESSION['user']['user_id'];
                $up_data['user_id']=$n_user_id;
                $up_data['password']=$o_user['password'];
                $up_data['qq']=$o_user['qq'];
                $up_data['mobile']=$o_user['mobile'];
                $up_data['email']=$o_user['email'];
//                $up_data['nickname']=$o_user['nickname'];
                $up_data['level_name']=$o_user['level_name'];
                $up_data['level']=$o_user['level'];
                $up_data['user_money']=$o_user['user_money']+$_SESSION['user']['user_money'];
                $res= M('users')->save($up_data);

                //订单，收藏夹 ,商品,求购，投诉

                $this->up_user_data($o_user_id,'goods',$n_user_id);
                $this->up_user_data($o_user_id,'goods_collect',$n_user_id);
                $this->up_user_data($o_user_id,'order1',$n_user_id);
                $this->up_user_data($o_user_id,'ask_buy',$n_user_id);
                $this->up_user_data($o_user_id,'complain',$n_user_id);

                //删除已被绑定的旧会员信息
                M('users')->where(array('user_id'=>$o_user_id))->delete();
                $this->success('绑定成功',U('User/index'));exit;
            }else{
                $this->error($res['msg']);exit;
            }
        }
        $this->display();
    }

  public function up_user_data($o_user_id,$db_name,$n_user_id){
        //收藏商品和订单可能存在两个账户同时下了某一件商品
        if($db_name=='order1'||$db_name=='goods_collect'){
            $db_name=='order1'?$str='order_id':$str='collect_id';//定义主键
            $n_list=M($db_name)->where(array('user_id'=>$n_user_id))->select();//查询新的账号的列表
            if(count($n_list)>0){
                $arr=array();
                foreach($n_list AS $v){
                    $arr[]=$v['goods_id'];//拼接筛选数组
                }
                $o_list=M($db_name)->where(array('user_id'=>$o_user_id))->select();//查询新账户数据列表
                foreach($o_list AS $vv){
                    if(in_array($vv['goods_id'],$arr)){//如果旧的数据，新账户已经存在  直接删除
                        M($db_name)->where(array($str=>$vv[$str]))->delete();
                    }else{
                        //旧账户的数据，跟新的账户数据不重复的，更新user_id
                        $up_data1[$str]=$vv[$str];
                        $up_data1['user_id']=$n_user_id;
                        M($db_name)->save($up_data1);
                    }
                }
                unset($arr);
            }else{
                //不存在冲突的，直接把旧的用户id 更新成新的用户id
                $where['user_id']=$o_user_id;
                $data['user_id']=$n_user_id;
                $res=M($db_name)->where($where)->save($data);
            }

        }else{
            //不存在冲突的，直接把旧的用户id 更新成新的用户id
            $where['user_id']=$o_user_id;
            $data['user_id']=$n_user_id;
            $res=M($db_name)->where($where)->save($data);
        }
  }
}